package com.xiaohudie.SGGJUC;

/**
 * @Author xiao hu die
 * @Date 2022/3/4 21:13
 * @Version 1.0
 */

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**创建资源类*/
class Ticket{
    /**固定的票数*/
    private int number =30;
    /**创建可重入锁*/
    private final ReentrantLock reentrantLock =new ReentrantLock();
    /**卖票的方法*/
    public void saleTicket(){
        /**上锁*/
        reentrantLock.lock();
        /**判断是否有票可以卖出*/
       try {
           if (number > 0) {
               number--;
               System.out.println(Thread.currentThread().getName() + "卖出了一张票" + "还剩下" + number + "张票");
           }
       }
       /**无论如何都会执行的方法*/
        finally {
            reentrantLock.unlock();
        }
    }
}

public class TestLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        ExecutorService executorService = new ThreadPoolExecutor(
                /**主线程数量*/
                3,
                /**最大线程数量*/
                5,
                /**线程等待时间*/
                2L,
                /**等待时间的单位时分秒*/
                TimeUnit.SECONDS,
                /**新建阻塞队列*/
                new ArrayBlockingQueue<>(3),
                /**线程工厂*/
                Executors.defaultThreadFactory(),
                /**拒绝策略,JDK默认4个*/
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        for (int i = 0; i < 30; i++) {
            executorService.execute(()-> ticket.saleTicket());
        }

    }
}
